<template>
  <div class="am-u-sm-12 am-u-md-12 am-u-lg-12 student-reg">
    <div class="widget am-cf">
      <div class="widget-head am-cf">
        <div class="widget-title am-fl">学生报名</div>
        <div class="widget-function am-fr">
          <!-- <button type="button" class="am-btn am-btn-primary" @click="showSearchList">更换学员</button> -->
          <el-button
            v-if="studentId"
            size="medium"
            type="primary"
            @click="showSearchList"
          >更换学员</el-button>
        </div>
      </div>
      <div class="am-padding-sm">
        <div
          class="select-wrap"
          v-if="!studentId"
        >
          <el-button
            size="medium"
            type="primary"
            @click="showSearchList"
          >选择学员</el-button>
        </div>
        <table
          style="width: 100%"
          v-else
        >
          <tr>
            <td
              rowspan="2"
              class="am-text-middle"
            >{{formData.name}}</td>
            <td>学号：{{formData.studentNo}}</td>
            <td>年级：{{formData.gradeName}}</td>
            <td>账户余额：{{mainAccount.balanceAmount | formatNumber(2)}} <span
                v-if="mainAccount.lockBalanceAmount && mainAccount.lockBalanceAmount > 0 "
                style="color: red;"
              >+{{mainAccount.lockBalanceAmount | formatNumber(2)}}</span></td>
          </tr>
          <tr>
            <td>电话：{{formData.phoneNo}}</td>
            <td>就读学校：{{formData.school}}</td>
            <td>绑定学员：
              <el-popover
                placement="top"
                ref="popover1"
                trigger="hover"
                @hide="popoverHide"
              >
                <div @click="hideQrea">
                  <div><img
                      class="bing-student-src-big"
                      :src="src"
                      alt=""
                    /></div>
                  <div class="qrSelect">
                    <div
                      class="qrSelectName"
                      @click="showQrArea"
                    >{{areaName}}
                      <div
                        class="qrAreaList"
                        v-show="isShowQrArea"
                      >
                        <div
                          @click="selectQrArea($event,item.areaTeamId)"
                          class="qrAreaItem"
                          v-for="item in areaTeams"
                          :key="item.areaTeamId"
                          :class="{active: item.areaTeamId === qrCodeAreateamId}"
                        >
                          {{item.name}}
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </el-popover>
              <img
                class="bing-student-src"
                :src="src"
                alt=""
                v-show="formData.cid"
                v-popover:popover1
              >
              <div
                class="el-icon-loading"
                v-show="!formData.cid"
              ></div>
            </td>
          </tr>
          <tr>
            <td></td>
            <td></td>
            <td></td>
            <td>
              <div class="btn-box">
                <el-button
                  size="small"
                  @click="handleRecharge"
                  type="primary"
                >充值</el-button>
                <el-button
                  size="small"
                  @click="handleWithdrawal"
                  type="primary"
                >提现</el-button>
                <el-button
                  size="small"
                  @click="handleTransfer"
                  type="primary"
                >转让</el-button>
                <el-button
                  size="small"
                  @click="handleOutTransfer"
                  type="primary"
                >TMS余额迁移</el-button>
                <el-button
                  size="small"
                  @click="mergeStudent"
                  type="primary"
                  v-if="hasWindowPermission('/main/enroll/student/search', 'mergeStudent')"
                >合并学员</el-button>
              </div>
            </td>
          </tr>
        </table>
      </div>
      <balance-withdrawals ref="withdrawals"></balance-withdrawals>
      <balance-recharge ref="recharge"></balance-recharge>
      <balance-transfer ref="transfer"></balance-transfer>
      <div class="widget-body am-fr">
        <div
          id="tabs"
          class="am-tabs"
          data-am-tabs="{noSwipe: 1}"
        >
          <ul class="am-tabs-nav am-nav am-nav-tabs">
            <li class="am-active first-one"><a href="javascript: void(0)">班级报名</a></li>
            <li><a
                href="javascript: void(0)"
                @click="tabIndex = 1"
              >待缴费</a></li>
            <li v-show="studentId"><a
                href="javascript: void(0)"
                @click="tabIndex = 2"
              >订单信息</a></li>
            <li v-show="studentId"><a
                href="javascript: void(0)"
                @click="tabIndex = 3"
              >在读班级</a></li>
            <li v-show="studentId"><a
                href="javascript: void(0)"
                @click="tabIndex = 4"
              >班级历史</a></li>
            <li v-show="studentId"><a
                href="javascript: void(0)"
                @click="tabIndex = 5"
              >诊断成绩</a></li>
            <li v-show="studentId"><a
                href="javascript: void(0)"
                @click="tabIndex = 6"
              >学生信息</a></li>
          </ul>
          <div class="am-tabs-bd am-tabs-bd-ofv">
            <div class="am-tab-panel am-active">
              <student-apply :studentId="studentId"></student-apply>
            </div>
            <div class="am-tab-panel">
              <reg-class-list
                :studentId="studentId"
                :studentName="formData.name"
                :studentInfo="formData"
              ></reg-class-list>
            </div>
            <div
              class="am-tab-panel"
              v-show="studentId"
            >
              <student-order-list
                :studentId="studentId"
                v-if="tabIndex == 2"
              ></student-order-list>
            </div>
            <div
              class="am-tab-panel"
              v-show="studentId"
            >
              <student-class-list
                :studentId="studentId"
                :studentInfo="formData"
                v-if="tabIndex == 3"
              ></student-class-list>
            </div>
            <div
              class="am-tab-panel"
              v-show="studentId"
            >
              <student-class-history-list
                :studentId="studentId"
                v-if="tabIndex == 4"
              ></student-class-history-list>
            </div>
            <div
              class="am-tab-panel"
              v-show="studentId"
            >
              <evaluation-score
                :studentId="studentId"
                v-if="tabIndex == 5"
              ></evaluation-score>
            </div>
            <div
              class="am-tab-panel"
              v-show="studentId"
            >
              <student-edit-from
                @saveCompleted="loadStudent"
                :studentId="studentId"
                v-if="tabIndex == 6"
              ></student-edit-from>
            </div>
          </div>
        </div>

      </div>
    </div>
    <window
      ref="win"
      title="查询"
    >
      <SearchStudentList
        @sureFunc="sureFunc"
        @closeWindow="closeWindow"
        @addStudent="addStudent"
        :isComponent="true"
      />
    </window>
    <window
      ref="mergeTips"
      title="提示"
    >
      <div>
        <div style="margin-bottom:20px">1、合并信息包括：报读信息、退费信息、账户余额、考勤等基本信息；</div>
        <div style="margin-bottom:20px">2、合并学员操作不可逆，请仔细确认将要合并的两个学员为同个学员！</div>
        <div>
          <el-button @click="mergeStudentTips('cancel')">取消</el-button>
          <el-button
            type="primary"
            @click="mergeStudentTips('sure')"
          >确定</el-button>
        </div>
      </div>
    </window>
    <window
      ref="mergeList"
      title="合并学生"
    >
      <div v-loading="tableLoading">
        <el-table
          :data="mergeTable"
          border
          empty-text="暂无数据"
          stripe
          style="min-width: 100%"
        >
          <el-table-column
            min-width="50"
            prop="studentNo"
            label="学号"
          >
          </el-table-column>
          <el-table-column
            min-width="50"
            label="姓名"
            prop="name"
          ></el-table-column>
          <el-table-column
            min-width="50"
            label="手机号"
            prop="phoneNo"
          >
          </el-table-column>
          <el-table-column
            min-width="50"
            label="最近报读校区"
            prop="lastRegCampusName"
          >
          </el-table-column>
          <el-table-column
            min-width="50"
            label="就读学校"
            prop="school"
          >
          </el-table-column>
          <el-table-column
            min-width="50"
            label="年级"
            prop="gradeName"
          >
          </el-table-column>
          <el-table-column
            min-width="50"
            label="地区"
            prop="location"
          >
          </el-table-column>
          <el-table-column
            min-width="50"
            label="出生日期"
          >
            <template scope="scope">
              {{scope.row.birthday | formatDate }}
            </template>
          </el-table-column>
          <el-table-column
            min-width="50"
            label="操作"
          >
            <template scope="scope">
              <div>
                <el-button @click="mergeSetting(scope.row)">合并</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </window>
    <window
      ref="mergeConfirm"
      title="确认"
    >
      <div style="margin: 10px 0">是否确定将学员“{{selectMergeStudent.name}}-{{selectMergeStudent.phoneNo}}”的信息，合并到学员“{{formData.name}}-{{formData.phoneNo}}”？</div>
      <div>
        <el-button @click="confirmMerge('cancel')">取消</el-button>
        <el-button
          type="primary"
          @click="confirmMerge('sure')"
        >确定</el-button>
      </div>
    </window>
  </div>
</template>
<style lang="less">
.qrSelect {
  padding-bottom: 10px;
  color: #000;
  background: #fff;
  .qrSelectName {
    position: relative;
    width: 100px;
    cursor: pointer;
    text-align: center;
    padding: 5px 0;
    border: 1px solid #ebebeb;
    margin: 0 auto;
  }
  .qrAreaList {
    background: #fff;
    position: absolute;
    border: 1px solid #ebebeb;
    overflow-y: auto;
    width: 100px;
    height: 160px;
    cursor: pointer;
    text-align: center;
    top: -160px;
    left: 0;
    .qrAreaItem {
      border-bottom: 1px solid #ebebeb;
      padding: 8px 0;
      &:last-child {
        border: none;
      }
      &.active {
        color: #fff;
        background: #0e90d2;
      }
    }
  }
}
.widget table {
  background: #eee;
}
.enroll-pay-table {
  &.el-tabs {
    height: 34px;
    color: #666;
    background: #eef1f6;
  }
  &.el-tabs--card > .el-tabs__header .el-tabs__item.is-active {
    background: #fff;
    color: #0e90d2;
    border-radius: 0;
  }
  .el-tabs__header {
    margin-bottom: 0;
    border-bottom: 1px solid #ddd;
    .el-tabs__nav-scroll {
      height: 34px;
    }
    .el-tabs__item {
      height: 34px;
      line-height: 34px;
    }
  }
}
.am-u-sm-12 tr {
  text-align: left;
}
.am-text-middle {
  font-size: 45px;
  text-align: center !important;
}
.select-wrap {
  background-color: #eee;
  padding: 30px 0;
  text-align: center;
  .el-button--primary {
    padding: 10px 35px;
    font-size: 18px;
  }
}
</style>
<style scoped>
.am-nav-tabs {
  background-color: #eef1f6;
}
.am-tabs-bd {
  border-color: #dfe6ec;
  user-select: text !important;
}
.am-nav-tabs > li > a {
  color: #666;
  font-size: 14px;
}
.am-nav-tabs > li.am-active > a {
  color: #0e90d2;
}
.am-nav > li > a:hover {
  background-color: #eef1f6;
  color: #333333;
}
.am-nav-tabs > li.am-active > a:hover {
  background-color: #fff;
  color: #0e90d2;
}
.bing-student-src {
  width: 27px;
  cursor: pointer;
  border: 1px solid #02c8c2;
}
.bing-student-src:hover {
  border-color: #000;
}
.btn-box {
  background: #eee;
  overflow: hidden;
  padding-top: 5px;
  padding-bottom: 10px;
}
</style>

<script>
import io from '../../lib/io'
import conf from '../../lib/conf'
import util from '../../lib/util'
import StudentEditForm from './StudentEditForm'
import StudentApply from './StudentApply'
import RegClassList from './RegClassList'
import StudentOrderList from './StudentOrderList'
import StudentClassList from './StudentClassList'
import ClassHistoryList from './ClassHistoryList'
import BalanceTransfer from './BalanceTransfer.vue'
import BalanceWithdrawals from './BalanceWithdrawals.vue'
import BalanceRecharge from './BalanceRecharge.vue'
import EvaluationScore from './EvaluationScore.vue'
import SearchStudentList from './SearchStudentList.vue'
import storage from '../../lib/storage'
export default {
  data() {
    let userInfo = storage.getCurrentUserInfo()
    return {
      studentId: this.$route.params.studentId
        ? this.$route.params.studentId
        : '',
      tabIndex: 0,
      codeUrl: '',
      formData: {},
      mainAccount: {},
      qrCodeAreateamId: '',
      areaName: '',
      isShowQrArea: false,
      userInfo,
      mergeTable: [],
      selectMergeStudent: {},
      tableLoading: false
    }
  },
  computed: {
    areaTeams: function() {
      return this.$root.config.areaTeams || []
    },
    src: function() {
      return (
        conf.baseApiPath +
        '/api/qrcode/encode?content=' +
        encodeURIComponent(this.codeUrl)
      )
    },
    notGuangzhouCodeUrl: function() {
      return `${conf.studentBasePath}/bind-student?areaTeamId=${
        this.qrCodeAreateamId
      }&studentId=${
        this.$route.params.studentId ? this.$route.params.studentId : ''
      }`
    }
  },
  components: {
    BalanceTransfer,
    BalanceWithdrawals,
    BalanceRecharge,
    EvaluationScore,
    'student-edit-from': StudentEditForm,
    'student-apply': StudentApply,
    'reg-class-list': RegClassList,
    'student-order-list': StudentOrderList,
    'student-class-list': StudentClassList,
    'student-class-history-list': ClassHistoryList,
    SearchStudentList
  },
  created: function() {
    if (this.studentId) {
      this.main()
    } else {
      this.init()
    }
  },
  updated() {
    if (
      !this.qrCodeAreateamId &&
      !util.isEmptyObj(this.formData) &&
      this.formData.cid
    ) {
      this.qrCodeAreateamId = this.areaTeams[0] && this.areaTeams[0].areaTeamId
      for (let item of this.areaTeams) {
        if (item.areaTeamId === this.qrCodeAreateamId) {
          this.areaName = item.name
          break
        }
      }
    }
  },
  mounted() {},
  watch: {
    qrCodeAreateamId() {
      this.disQrcode()
    },
    studentId() {
      this.loadStudent().then(() => {
        this.disQrcode()
      })
      this.loadMainAccount()
    },
    $route(to, from) {
      let url =
        conf.studentBasePath +
        '/bind-student?studentId=' +
        (to.params.studentId ? to.params.studentId : '')
      this.src =
        conf.baseApiPath +
        '/api/qrcode/encode?content=' +
        encodeURIComponent(url)
      if (to.path == '/main/enroll/student/search') {
        this.studentId = ''
      }
    }
  },
  methods: {
    confirmMerge(type) {
      if (type === 'sure') {
        this.$showLoading()
        io.post(
          io.mergeStudent,
          {
            originStudentId: this.selectMergeStudent.studentId,
            targetStudentId: this.formData.studentId,
            cid: this.formData.cid
          },
          ret => {
            this.$hiddenLoading()
            if (ret.success) {
              this.loadSameNameStudent('noHide')
              this.main()
              this.$refs.mergeConfirm.close()
            } else {
              this.$alert(ret.desc)
            }
          }
        )
      } else {
        this.$refs.mergeConfirm.close()
      }
    },
    mergeSetting(row) {
      this.selectMergeStudent = row
      this.$refs.mergeConfirm.show({
        width: 600
      })
    },
    mergeStudent() {
      this.$refs.mergeTips.show({
        width: 600
      })
    },
    mergeStudentTips(type) {
      this.$refs.mergeTips.close()
      if (type === 'sure') {
        this.loadSameNameStudent()
      }
    },
    disQrcode() {
      if (this.qrCodeAreateamId !== '564701030634225664') {
        this.codeUrl = this.notGuangzhouCodeUrl
      } else {
        this.codeUrl = `${
          conf.qrCodeBindPath
        }?uuid=${util.getUuid()}&bizSystemId=2&stuMemberId=${
          this.formData.cid
        }&stuId=${this.studentId}&shareUserId=${
          this.userInfo.userId
        }&shareUserPhone=${this.userInfo.phoneNo}`
      }

      for (let item of this.areaTeams) {
        if (item.areaTeamId === this.qrCodeAreateamId) {
          this.areaName = item.name
          break
        }
      }
    },
    main() {
      this.loadStudent().then(() => {
        if (this.formData.cid) {
          this.init()
        }
      })
    },
    init() {
      this.loadMainAccount()
      var _this = this
      this.$root.$on('mainAccount:change', function() {
        _this.loadMainAccount()
      })
      this.$root.$on('studentReg:changeTabIndex', function(tabIndex) {
        _this.tabIndex = tabIndex
        console.log(_this.tabIndex)
      })

      console.log(_this.tabIndex)
      //init tabs
      $('#tabs').tabs()
    },
    hideQrea() {
      this.isShowQrArea = false
    },
    selectQrArea(e, id) {
      e.stopPropagation()
      this.qrCodeAreateamId = id
      this.isShowQrArea = false
    },
    popoverHide() {
      this.isShowQrArea = false
    },
    showQrArea(e) {
      e.stopPropagation()
      this.isShowQrArea = !this.isShowQrArea
    },
    addStudent() {
      this.$refs.win.close()
    },
    sureFunc(studentId) {
      this.$refs.win.close()
      this.studentId = studentId
      document.querySelector('.first-one a') &&
        document.querySelector('.first-one a').click()
      this.tabIndex = 0
    },
    closeWindow() {
      this.$refs.win.close()
    },
    showSearchList() {
      this.$refs.win.show({
        width: 1200,
        height: 800
      })
    },
    handleWithdrawal() {
      this.$refs.withdrawals.studentId = this.studentId
      this.$refs.withdrawals.balanceAmount = Number(
        this.mainAccount.balanceAmount
      ).toFixed(2)
      this.$refs.withdrawals.show()
    },
    handleRecharge() {
      this.$refs.recharge.studentId = this.studentId
      this.$refs.recharge.balanceAmount = Number(
        this.mainAccount.balanceAmount
      ).toFixed(2)
      this.$refs.recharge.show()
    },
    handleTransfer() {
      this.$refs.transfer.studentId = this.studentId
      this.$refs.transfer.balanceAmount = Number(
        this.mainAccount.balanceAmount
      ).toFixed(2)
      this.$refs.transfer.show()
    },
    handleOutTransfer() {
      io.post(
        io.queryStudentDealBalance,
        { studentId: this.studentId },
        ret => {
          if (ret.success) {
            let amount = Number(ret.data.availableMoney).toFixed(2)
            let mes =
              ret.data.stuName +
              '在TMS的账户余额：' +
              amount +
              '元。' +
              '您确定将该生在TMS的所有余额转移到本系统？'
            this.$confirm(mes, () => {
              this.confirmTransferTmsBalance(amount)
            })
          } else {
            this.$alert(ret.desc)
          }
        }
      )
    },
    confirmTransferTmsBalance(amount) {
      io.post(
        io.comfirmTransferTmsBalance,
        { studentId: this.studentId, amount: amount },
        ret => {
          if (ret.success) {
            this.loadMainAccount()
            this.$toast('余额迁移成功')
          } else {
            this.$alert(ret.desc)
          }
        }
      )
    },
    loadMainAccount: function() {
      var _this = this
      io.post(
        io.apiAdminStudentMainAccount,
        {
          studentId: _this.studentId
        },
        function(ret) {
          if (ret.success) {
            _this.mainAccount = ret.data || { balanceAmount: 0 }
          } else {
            _this.$alert(ret.desc)
          }
        }
      )
    },
    loadStudent: function() {
      return new Promise((resolve, reject) => {
        var _this = this
        io.post(
          io.apiAdminStudentDetail,
          { studentId: _this.studentId },
          function(ret) {
            if (ret.success) {
              ret.data.student.birthday = util.formatDate(
                ret.data.student.birthday
              )
              _this.formData = ret.data.student
              resolve()
            }
          }
        )
      })
    },
    loadSameNameStudent(type) {
      this.tableLoading = true
      io.post(
        io.findStudentBySameName,
        { studentId: this.formData.studentId },
        ret => {
          this.tableLoading = false
          if (ret.success) {
            this.mergeTable = ret.data
            if (type !== 'noHide') {
              this.$refs.mergeList.show({
                width: 900
              })
            }
          } else {
            _this.$alert(ret.desc)
          }
        }
      )
    }
  }
}
</script>
